package com.atguigu.gulimall.sso.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/loginPage")
    public String loginPage(String redirectUrl, Model model, @CookieValue(value = "sso_server", required = false) String sso_server) {
        model.addAttribute("redirectUrl", redirectUrl);
        if (!StringUtils.isEmpty(sso_server)){
            //说明之前有人登陆过
            System.out.println("sso_server:" + sso_server);
            return "redirect:" + redirectUrl + "?token=" + sso_server;
        }
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, @RequestParam String redirectUrl, HttpSession session, HttpServletResponse response) {

        String uuid = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(uuid, username, 30_000, TimeUnit.MILLISECONDS);

        System.out.println("uuid:" + uuid);
        Cookie sso_server = new Cookie("sso_server", uuid);
        response.addCookie(sso_server);

        return "redirect:" + redirectUrl + "?token=" + uuid;
    }
}
